//导入课程目标模型
const { T_exam_target } = require('../models/t_exam_target')
const { T_exam_target_to_question } = require('../models/t_exam_target_to_question')

// 基于科目ID查询课程目标
exports.get_target_by_subjectID = async (req, res) => {
  const subjectId = req.params.id;

  try {
    const targets = await T_exam_target.findAll({
      where: { sub_id: subjectId }
    });

    if (targets.length > 0) {
      res.json({
        "code": 200,
        "msg": "查询成功",
        "data": targets
      });
    } else {
      res.json({
        "code": 404,
        "msg": "未找到该科目的课程目标"
      });
    }
  } catch (error) {
    res.json({
      "code": 500,
      "msg": "查询失败，请重试"
    });
  }
}

// //通过id来获取课程目标
exports.getT_targetById = async (req, res) => {
  const { id } = req.params;
  console.log('ID is:', id);

  try {
    const t_target = await T_exam_target.findByPk(id);//根据id查询
    if (t_target) {
      res.json({
        "code": 200,
        "msg": "查询成功",
        "data": t_target,
      });
    } else {
      res.json({
        "code": 404,
        "mag": "查询失败,该课程目标id不存在",
      })
    };
  } catch (error) {
    res.json({
      "code": 500,
      "msg": error.message
    });
  }
};

//导入标签模型
const { T_exam_label } = require('../models/t_exam_label')
//添加课程目标
exports.create_target = async (req, res) => {
  const body = req.body;
  console.log(body);
  try {
    const newTarget = await T_exam_target.create({
      target_name: body.target_name,
      target_desc: body.target_desc, // 假设前端传过来的是数组形式的 target_desc
      target_content: body.target_content,
      sub_id: body.sub_id
    });

    // 将 target_desc 插入到 t_exam_labels 表中，但先检查是否已存在相同标签内容
    const labelsPromises = body.target_desc.map(async (label) => {
      const existingLabel = await T_exam_label.findOne({ where: { label: label, sub_id: body.sub_id } });
      if (!existingLabel) {

        //良帅开始动手
        T_exam_target_to_question.create({
          subid: body.sub_id,
          targetId: newTarget.id,
          paperType: "A"
        })

        T_exam_target_to_question.create({
          subid: body.sub_id,
          targetId: newTarget.id,
          paperType: "B"
        })

        //良帅结束动手
        return await T_exam_label.create({
          label: label,
          sub_id: body.sub_id
        });
      } else {
        console.log(`Label '${label}' already exists for sub_id ${body.sub_id}. Skipping insertion.`);
        return null; // 返回null表示跳过插入操作
      }
    });

    const insertedLabels = await Promise.all(labelsPromises);
    const filteredLabels = insertedLabels.filter(label => label !== null); // 过滤掉返回null的标签

    res.json({
      "code": 1,
      "msg": '创建成功',
      "data": {
        newTarget,
        insertedLabels: filteredLabels
      },
    });
  } catch (error) {
    res.json({
      "code": 500,
      "msg": error.message,
    });
  }
};

//删除课程目标
exports.delete_targetById = async (req, res) => {
  const { id } = req.params;
  console.log(id);
  try {
    const deletedRows = await T_exam_target.destroy({
      where: { id },
    });
    //良帅开始动手
    T_exam_target_to_question.destroy({
      where: {
        targetId: id
      }
    })

    //良帅结束动手
    if (deletedRows > 0) {
      res.json({
        "code": 1,
        "msg": '删除成功',
      });
    } else {
      res.json({
        "code": 404,
        "msg": `不存在该课程目标`,
      });
    }
  } catch (error) {
    res.json({
      "code": 500,
      "msg": error.message,
    });
  }
};


const { Sequelize } = require('sequelize');
//更新课程目标信息
exports.update_target = async (req, res) => {
  const { id } = req.params;
  const { target_name, target_desc, target_content, sub_id } = req.body;

  try {
    const [updateRows] = await T_exam_target.update(
      {
        target_name: target_name,
        target_desc: target_desc,
        target_content: target_content,
        sub_id: sub_id
      },
      { where: { id: id } }
    );

    if (updateRows === 0) { // 如果没有更新任何记录
      res.json({
        "code": 400,
        "msg": "更新失败，该id不存在",
      });
    } else { // 如果更新成功
      // 遍历 target_desc，对标签表进行操作
      const promises = target_desc.map(async (label) => {
        const [labelInstance, created] = await T_exam_label.findOrCreate({
          where: { label: label, sub_id: sub_id },
          defaults: { label: label, sub_id: sub_id }
        });
        if (created) {
          console.log(`Label '${label}' created for sub_id ${sub_id}`);
        } else {
          console.log(`Label '${label}' already exists for sub_id ${sub_id}.`);
        }
      });

      await Promise.all(promises);

      res.json({
        "code": 200,
        "msg": "更新成功",
      });
    }

  } catch (error) {
    res.json({
      "code": 500,
      "msg": error.message,
    });
  }
};